package net.mukia.web;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import net.mukia.model.Account;
import net.mukia.model.Group;
import net.mukia.service.AccountService;
import net.mukia.service.GroupService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/group")
@SessionAttributes(types = { Account.class })
public class GroupController {

	@RequestMapping(value = "/create")
	public void create() {

	}

	// create a group
	@RequestMapping(value = "/create!save")
	public String create(@ModelAttribute("group") Group group,
			@ModelAttribute(Account.SESSION_PARAMETER) Account account) {
		List<Account> accountList = new ArrayList<Account>();
		accountList.add(account);
		group.setAccountList(accountList);
		group.setAccount(account);
		groupService.save(group);
		return "redirect:list";
	}

	// the list of group
	@RequestMapping(value = "/list")
	public void list(Model model) {
		List<Group> groupList = groupService.queryAll(null);
		model.addAttribute("groupList", groupList);
	}

	// group detail
	@RequestMapping(value = "/{groupId}")
	public String detail(@PathVariable long groupId, Model model) {
		Group group = groupService.queryOne(groupId);
		model.addAttribute("group", group);
		return "/group/detail";
	}

	// join a group
	@RequestMapping("/join")
	public void join(Model model) {
		List<Group> groupList = groupService.queryAll(null);
		model.addAttribute("groupList", groupList);
	}
	@RequestMapping("/join/{groupId}")
	public String join(@PathVariable long groupId,@ModelAttribute(Account.SESSION_PARAMETER) Account account,Model model){
		Group group = groupService.queryOne(groupId);
		group.getAccountList().add(account);
		groupService.update(group);
		model.addAttribute("group", group);
		return "/group/join_success";
	}

	@Resource
	private GroupService groupService;

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}
	

}
